#include <iostream>
#include <unistd.h>
#include <sys/fcntl.h>

void nonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);    
    if(fl < 0) {
        std::perror("fcntl error");
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
} 

int main()
{
    nonBlock(0); // 设置0号文件描述符为非阻塞
    char buffer[1024];
    while(true) {
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if(n > 0) {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else if(n == 0) {
            std::cout << "read end" << std::endl;
        }
        else {
            // 当read返回值为0时，我们无法判断read到底是出错了，还是因为条件不满足返回了
            if(errno == EAGAIN || errno == EWOULDBLOCK) {
                std::cout << "数据还没有准备好" << std::endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR) {
                std::cout << "read 被信号中断" << std::endl;
                continue;
            }
            else {
                // 此时才是真正出错了
                std::cout << "read error" << std::endl;
            }
        }
    }
    return 0;
}